/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SssServer {
  public static Logger getLogger() {
    return SssServer.getLogger(SssServer.class);
  }

  public static Logger getLogger(Class<?> klass) {
    return LoggerFactory.getLogger(klass);
  }

  public static void initLogging() throws Exception {
    /**
     * initialize logging mechanism
     */
//    PropertyConfigurator
//      .configure(Thread.currentThread().getContextClassLoader()
//                 .getResource("conf/mapreduce.log4j.server.properties"));
//    PropertyConfigurator
//      .configure(Resources.getConfigDirectory() + "/mapreduce.log4j.server.properties");
  }

  public static void main(String[] args) throws Exception {
    SssServer.initLogging();
    final Logger logger = SssServer.getLogger();

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
          logger.error("Uncached exception: exit", e);
          System.exit(-1);
        }
      });

    if (args.length != 2) {
      logger.error("failed to start server process");
      logger.error("SssServer <port> <id>");
      System.exit(-1);
    }

    int id = Integer.parseInt(args[1]);
    int pid = org.sss.util.Misc.getPid();

    Runtime.getRuntime().addShutdownHook(new ShutdownSssServer(pid, id));

    logger.info("starting server process {} ({})", id, pid);
    logger.info("max memory {} bytes", Runtime.getRuntime().maxMemory());

    int rmiRegistryPort = Integer.parseInt(args[0]);
    Registry registry = LocateRegistry.createRegistry(rmiRegistryPort);

    registry.bind("SssServerImpl", new SssServerImpl(registry, id));
  }
}

class ShutdownSssServer extends Thread {
  private final int pid;
  private final int sid;

  public ShutdownSssServer(int pid, int sid) {
    super();
    this.pid = pid;
    this.sid = sid;
  }

  @Override
  public void run() {
    Logger logger = SssServer.getLogger();
    logger.info("stopping server process {} ({})", sid, pid);
  }
}
